import React, {Component} from "react";
import {Col, DatePicker, Form, Input, Row, Select, message, InputNumber} from "antd";
import moment from 'moment';
import {getOptions, getCrmRecordFromSql, getCrmRecordById, isBlank} from "../util/util";
import '../styles.css'; // 引入CSS文件

const dateFormat = 'YYYY-MM-DD';

const ZOHO = window.ZOHO;
const {TextArea} = Input;
let timeout;
let currentValue;

class contractForm extends Component {

    constructor(props) {
        super(props);
        this.formRef = React.createRef();

        this.state = {
            // 客户
            accountOptions: [],
            // 合同号
            FcontractNoOptions: [],
            // 工厂
            plantOptions: [],
            // 发货人代码
            ShipperInformationOptions: [],
            // 国家
            StatesOptions: [],
            // 币种
            CurrencyOptions: [],
            FcontractNo: []
        };
    }

    async componentDidMount() {
        const {current} = this.formRef;

        let FcontractNoOptions = [];
        let accountOptions = [];
        let plantOptions = [];
        let ShipperInformationOptions = [];
        let CurrencyOptions = [];
        let StatesOptions = [];
        try {
            let Currencytypes = await getOptions("Currencytype");
            CurrencyOptions = Currencytypes.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let accounts = await getOptions("Accounts");
            accountOptions = accounts.map(item => ({
                value: item.id,
                label: item.Account_Name,
            }));
            let Plants = await getOptions("Plant");
            plantOptions = Plants.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let Foreignsacontracts = await getOptions("Foreignsacontract");
            FcontractNoOptions = Foreignsacontracts.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let States = await getOptions("States");
            StatesOptions = States.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let ShipperInformations = await getOptions("ShipperInformation");
            ShipperInformationOptions = ShipperInformations.map(item => ({
                value: item.id,
                label: item.Name,
            }));
        } catch (error) {
            console.error(error);
        }
        let FcontractNo = [];
        if (window.id !== undefined) {
            try {

                const formdata = await getCrmRecordById("PSNotice", window.id);
                formdata.ContractDate = isBlank(formdata.ContractDate) ? undefined : moment(formdata.ContractDate);
                formdata.Deliverytime = isBlank(formdata.Deliverytime) ? undefined : moment(formdata.Deliverytime);

                formdata.Currencys = {
                    value: formdata.Currencys?.id,
                    label: formdata.Currencys?.name,
                };
                formdata.Account = {
                    value: formdata.Account?.id,
                    label: formdata.Account?.name,
                }
                formdata.Plant = {
                    value: formdata.Plant?.id,
                    label: formdata.Plant?.name,
                }
                formdata.ShipperInformation = {
                    value: formdata.ShipperInformation?.id,
                    label: formdata.ShipperInformation?.name,
                }
                formdata.States = {
                    value: formdata.States?.id,
                    label: formdata.States?.name,
                }
                formdata.FcontractNo?.map(item => {
                    item.value = item.field1.id
                    item.label = item.field1.name
                    item.key = item.field1.id
                    delete item.field1;

                })
                FcontractNo = formdata.FcontractNo
                current.setFieldsValue(formdata);
                console.log(formdata)
            } catch (error) {
                console.error(error);
            }
        }
        console.log(FcontractNo)
        this.setState({ // 客户
            accountOptions: accountOptions,
            plantOptions: plantOptions,
            ShipperInformationOptions: ShipperInformationOptions,
            FcontractNoOptions: FcontractNoOptions,
            CurrencyOptions: CurrencyOptions,
            StatesOptions: StatesOptions,
            FcontractNo: FcontractNo
        });
    }


    changeFcontractNo = (values) => {
        const {current} = this.formRef;
        current.setFieldValue("FcontractNo", values);
        console.log(values)
        if (values.length === 0) {
            current.setFieldValue("Account", {
                value: "",
                label: "",
            });
            current.setFieldValue("AccountOrderNo", "");
            current.setFieldValue("ShipperInformation", {
                value: "",
                label: "",
            });
            current.setFieldValue("ShipperInformationName", "");
            current.setFieldValue("ContractDate", "");
            current.setFieldValue("Currencys", {
                value: "",
                label: "",
            });
            current.setFieldValue("States", {
                value: "",
                label: "",
            });
            this.setState({ // 客户
                FcontractNo: values
            });
            return
        }
        ZOHO.CRM.API.getRecord({
            Entity: "Foreignsacontract", approved: "both", RecordID: values[0]?.id
        }).then(data => {

            current.setFieldValue("Account", {
                value: data.data[0].Account?.id,
                label: data.data[0].Account?.name,
            });
            current.setFieldValue("AccountOrderNo", data.data[0].AccountOrderNo);
            current.setFieldValue("ShipperInformation", {
                value: data.data[0].Header?.id,
                label: data.data[0].Header?.name,
            });
            current.setFieldValue("ShipperInformationName", data.data[0].ShipperInformationName);
            current.setFieldValue("ContractDate", moment(data.data[0].ContractDate));
            current.setFieldValue("ProcurementTerms", data.data[0].PayTerms);

            current.setFieldValue("Currencys", {
                value: data.data[0].Currencys?.id,
                label: data.data[0].Currencys?.name,
            });
            current.setFieldValue("States", {
                value: data.data[0].TradingCountry?.id,
                label: data.data[0].TradingCountry?.name,
            });
        })
        this.setState({ // 客户
            FcontractNo: values
        });
    }
    changeAccount = async (value) => {
        const {current} = this.formRef;
        current.setFieldValue("Account", {
            value: value.key,
            label: value.label
        })
    }
    changePlant = (value) => {
        const {current} = this.formRef;
        current.setFieldValue("Plant", {
            value: value.key,
            label: value.label
        })
        ZOHO.CRM.API.getRecord({
            Entity: "Plant", approved: "both", RecordID: value.key
        }).then(data => {
            current.setFieldValue("PlantName", data.data[0].FullName)
        })
    }
    changeShipperInformation = (value) => {
        const {current} = this.formRef;
        current.setFieldValue("ShipperInformation", {
            value: value.key,
            label: value.label
        })
        ZOHO.CRM.API.getRecord({
            Entity: "ShipperInformation", approved: "both", RecordID: value.key
        }).then(data => {
            current.setFieldValue("ShipperInformationName", data.data[0].China_Name)
        })
    }
    changeStates = (value) => {
        const {current} = this.formRef;
        current.setFieldValue("States", {
            value: value.key,
            label: value.label
        })
    }
    changeCurrencys = (value) => {
        const {current} = this.formRef;
        current.setFieldValue("Currencys", {
            value: value.key,
            label: value.label
        })
    }


    handleSearch = (value) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        currentValue = value;
        const fake = () => {
            getCrmRecordFromSql(`select id,Name from Foreignsacontract where Name like '%${value}%'`).then(result => {
                let FcontractNoOptions = result.map((item) => ({
                    value: item.id,
                    label: item.Name,
                }));
                this.setState({FcontractNoOptions: FcontractNoOptions});
            })
        };
        if (value) {
            timeout = setTimeout(fake, 300);
        }
    }

    handleCancel = () => {
        const {current} = this.formRef;
        current.resetFields();
    };

    render() {
        const {
            accountOptions,
            plantOptions,
            FcontractNoOptions,
            ShipperInformationOptions,
            CurrencyOptions,
            StatesOptions,
            FcontractNo
        } = this.state;
        const {Item} = Form;
        return (
            <div className="body">

                <Form ref={this.formRef}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Item label="生产通知单号" name="Name" labelAlign="right"
                                  rules={[{required: true, message: '请输入生产通知单号'}]}>
                                <Input className="input-field"/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="外销合同号" name="FcontractNo" labelAlign="right">
                                <Select
                                    mode="multiple"
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changeFcontractNo}
                                    options={FcontractNoOptions}
                                    optionLabelProp="label"
                                    filterOption={false}
                                    onSearch={this.handleSearch}
                                    value={FcontractNo}
                                /> </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="客户" name="Account" labelAlign="right"
                                  rules={[{required: true, message: '请选择客户'}]}>
                                <Select
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changeAccount}
                                    options={accountOptions}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                />
                            </Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>

                        <Col span={8}>
                            <Item label="发货人代码" name="ShipperInformation">
                                <Select
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changeShipperInformation}
                                    options={ShipperInformationOptions}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                />
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="发货人名称" name="ShipperInformationName">
                                <Input className="input-field" disabled={true}/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="总数量(袋)" name="Total_P" labelAlign="right">
                                <InputNumber className="input-field" step={1}/>
                            </Item>
                        </Col>

                    </Row>

                    <Row gutter={16}>

                        <Col span={8}>
                            <Item label="客户订单号" name="AccountOrderNo">
                                <Input className="input-field"/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="合同日期" name="ContractDate">
                                <DatePicker className="input-field" format={dateFormat}/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="毛重" name="Grossweight">
                                <InputNumber className="input-field" step={0.1}/>
                            </Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Item label="工厂代码" name="Plant">
                                <Select
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changePlant}
                                    options={plantOptions}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                />
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="工厂名称" name="PlantName">
                                <Input className="input-field" disabled={true}/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="净重" name="Netweight">
                                <InputNumber className="input-field" step={0.1}/>
                            </Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Item label="合同类型" name="ContractType">
                                <Select className="input-field">
                                    <Select.Option value="生产通知单">生产通知单</Select.Option>
                                    <Select.Option value="生产通知单">采购订单</Select.Option>
                                </Select>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="货好时间" name="Deliverytime">
                                <DatePicker className="input-field" format={dateFormat}/>
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="总箱数" name="Total_B">
                                <InputNumber className="input-field" step={1}/>
                            </Item>
                        </Col>


                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Item label="币种" name="Currencys" labelAlign="right">
                                <Select
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changeCurrencys}
                                    options={CurrencyOptions}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                />
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="出口国家" name="States" labelAlign="right">
                                <Select
                                    labelInValue
                                    className="input-field"
                                    showSearch
                                    onChange={this.changeStates}
                                    options={StatesOptions}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                />
                            </Item>
                        </Col>
                        <Col span={8}>
                            <Item label="采购条款" name="ProcurementTerms">
                                <TextArea className="input-field" rows={4}/>
                            </Item>
                        </Col>
                    </Row>

                </Form>


            </div>

        );
    }
}

export default contractForm;